package com.mrzhou.msg.controller;

import com.mrzhou.common.constant.CommonConstant;
import com.mrzhou.common.entity.msg.MailInfo;
import com.mrzhou.common.util.ValidUtil;
import com.mrzhou.core.tool.api.R;
import com.mrzhou.core.tool.utils.DataUtil;
import com.mrzhou.core.tool.utils.DigestUtil;
import com.mrzhou.data.support.RedisService;
import com.mrzhou.msg.service.IMailService;
import com.mrzhou.msg.vo.req.ValidMailPhoneReq;
import com.mrzhou.web.util.WebUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Api(tags = "发送邮件相关接口")
public class SendMailController {

    @Autowired
    private IMailService mailService;
    @Autowired
    private RedisService redisService;

    @PostMapping("send-email_phone-code")
    @ApiOperation("获取邮箱验证码")
    public R<String> sendEmailCode(@ApiParam(value = "邮箱或者手机号", required = true) @RequestParam("mailPhone") String mailPhone,
                                   @ApiParam(value = "验证码类型, 1注册, 2登录,3忘记密码", required = true) @RequestParam("type")  int type) {
        // 参数校验
        if (!ValidUtil.isEmail(mailPhone)) {
            return R.fail("请输入正确的邮箱地址");
        }
        if(!ValidUtil.validMailCodeType(type)) {
            return R.fail("非法的验证码类型: " + type);
        }

        String mailCode = DataUtil.randomNum(CommonConstant.MAIL_CODE_LENGTH);

        String ip = WebUtil.getIp();
        String key = CommonConstant.MAIL_CODE_KEY_PREFIX + DigestUtil.md5Hex(mailPhone  + ":" + ip + ":" + type);

        // 在验证码有效期类, 同一个人不能获取两次相同的mailCode
        if (redisService.exists(key)) {
            return R.fail("你已获取邮箱验证码；请稍后重试！");
        }

        MailInfo mailInfo = new MailInfo();
        mailInfo.setIp(ip);
        mailInfo.setMail(mailPhone);
        mailInfo.setMailCode(mailCode);
        mailInfo.setStatus(CommonConstant.MAIL_CODE_STATUS_INIT);
        R<String> result = mailService.sendSimpleMail("登录邮箱验证码", "你本次使用的邮箱验证码为: " + mailCode + "; 验证码5分钟内有效, 请勿泄露给他人！", mailPhone);
         // 保存Redis的数据
        redisService.set(key, mailInfo, CommonConstant.MAIL_CODE_TIME_OUT);
        return result;
    }

    /**
     * 校验邮箱验证码
     */
    @PostMapping("valid-mail-code")
    @ApiOperation("校验邮箱验证码")
    public R<String> validMailCode(@Validated ValidMailPhoneReq req) {
        return mailService.validMailCode(req);
    }

}
